#include <shobjidl.h>
#include <vector>
#include <string>


#include <windows.h>
#include <string>

std::vector<std::string> SelectMultiplePDFFiles()
{
    std::vector<std::string> filePaths;
    
    // 初始化COM
    CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
    
    IFileOpenDialog* pFileDialog = nullptr;
    
    // 创建文件对话框对象
    if (SUCCEEDED(CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_ALL, 
                                  IID_IFileOpenDialog, reinterpret_cast<void**>(&pFileDialog))))
    {
        // 设置允许多选
        DWORD dwOptions;
        if (SUCCEEDED(pFileDialog->GetOptions(&dwOptions)))
        {
            pFileDialog->SetOptions(dwOptions | FOS_ALLOWMULTISELECT);
        }
        
        // 设置文件类型过滤器 - PDF文件
        COMDLG_FILTERSPEC fileTypes[] = { {L"PDF Files", L"*.pdf"} };
        pFileDialog->SetFileTypes(1, fileTypes);
        pFileDialog->SetFileTypeIndex(1); // 默认选择PDF过滤器
        
        // 显示对话框
        if (SUCCEEDED(pFileDialog->Show(NULL)))
        {
            IShellItemArray* pItemArray = nullptr;
            // 使用正确的方法获取多选结果
            if (SUCCEEDED(pFileDialog->GetResults(&pItemArray)))
            {
                DWORD count = 0;
                if (SUCCEEDED(pItemArray->GetCount(&count)))
                {
                    for (DWORD i = 0; i < count; ++i)
                    {
                        IShellItem* pItem = nullptr;
                        if (SUCCEEDED(pItemArray->GetItemAt(i, &pItem)))
                        {
                            PWSTR pszFilePath = nullptr;
                            if (SUCCEEDED(pItem->GetDisplayName(SIGDN_FILESYSPATH, &pszFilePath)))
                            {
                                // 将宽字符串转换为ANSI字符串
                                int len = WideCharToMultiByte(CP_ACP, 0, pszFilePath, -1, NULL, 0, NULL, NULL);
                                if (len > 0)
                                {
                                    char* ansiPath = new char[len];
                                    WideCharToMultiByte(CP_ACP, 0, pszFilePath, -1, ansiPath, len, NULL, NULL);
                                    filePaths.push_back(ansiPath);
                                    delete[] ansiPath;
                                }
                                CoTaskMemFree(pszFilePath);
                            }
                            pItem->Release();
                        }
                    }
                }
                pItemArray->Release();
            }
        }
        pFileDialog->Release();
    }
    
    CoUninitialize();
    return filePaths;
}

int main(int argc, char const *argv[])
{
    auto pdfList = SelectMultiplePDFFiles();
    for(auto &file : pdfList)
    {
     
        OutputDebugStringA(file.c_str());
        
    }
    return 0;
}
